import { fromJS } from 'immutable'

import { getAccount } from '../../api/accountApi'

import { TRADE_ASSETS_ACTION } from '../reducers/tradeAssetsReducer'

/**
 * 轮询资金
 * @returns {function(...[*]=)}
 */
export function pollAssets () {
  const accountRequest = (dispatch) => {
    getAccount().then(
      result => {
        const assetsList = result.data || []
        const assetsMap = {}
        assetsList.forEach(assets => {
          const currency = assets.Currency
          assetsMap[currency] = assets
        })
        dispatch({
          type: TRADE_ASSETS_ACTION,
          data: {
            assets: fromJS(assetsMap)
          }
        })
        setTimeout(() => {
          accountRequest(dispatch)
        }, 5000)
      }
    ).catch(_ => {
      setTimeout(() => {
        accountRequest(dispatch)
      }, 5000)
    })
  }
  return dispatch => {
    accountRequest(dispatch)
  }
}
